const express = require('express');
const router = express.Router();
const { User } = require('../models');
const { Op } = require('sequelize');
const { BadRequestError, UnauthorizedError, NotFoundError } = require('../utils/errors');
const { success, failure } = require('../utils/responses');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
// 注册

router.post('/register', async (req, res) => {
    try {
        const body = {
            email: req.body.email,
            username: req.body.username,
            nickname: req.body.nickname,
            password: req.body.password,
            sex: 2,
            role:0
        }
        const user = await User.create(body)
        delete user.dataValues.password;
        success(res, '创建用户成功。', { user }, 201);
    }catch (error) {
        failure(res, error);
    }
})
//登录
// 1.验证用户名和邮箱是否存在 Op.or
// 2.验证密码是否正确--bcrypt.compareSync(password, user.password)
// 3.生成token--npm i jsonwebtoken
// 4.生成密匙--npm i dotenv, 引入crypto

// Op.or 会将数组内的多个条件组合成“或”逻辑，类似 SQL 中的 WHERE email = ? OR username = ?

router.post('/login', async (req, res) => {
    try {
        const { login, password } = req.body;
        if(!login) {
          throw new BadRequestError('邮箱/用户名必须填写。');
        }
        
        if(!password) {
          throw new BadRequestError('密码必须填写。');
        }
        const condition = {
          [Op.or]: [
            { email: login },
            { username: login }
          ]
        };
        const user = await User.findOne({ where: condition });
        if(!user) {
          throw new NotFoundError('用户不存在。');
        }
        console.log("🚀 ~ router.post ~ user:", user.id)
        const isPasswordValid = bcrypt.compareSync(password, user.password);
        if (!isPasswordValid) {
          throw new UnauthorizedError('密码错误。');
        }
        // const crypto = require('crypto');
        // console.log(crypto.randomBytes(32).toString('hex'));
        const token =jwt.sign({
         userId: user.id, 
        }, process.env.SECRET, { expiresIn: '1d' });
        success(res, '登录成功。', { token });
       
    } catch (error) {
        failure(res, error);
     }
})
module.exports = router;